package com.sagframe.sagacity.sqltoy.plus.multi;

import com.sagframe.sagacity.sqltoy.plus.MultiFiledMappingStrategy;
import com.sagframe.sagacity.sqltoy.plus.conditions.ISqlSegment;
import com.sagframe.sagacity.sqltoy.plus.conditions.eumn.CompareEnum;
import com.sagframe.sagacity.sqltoy.plus.conditions.eumn.SqlKeyword;
import com.sagframe.sagacity.sqltoy.plus.conditions.toolkit.FiledNature;
import com.sagframe.sagacity.sqltoy.plus.conditions.toolkit.StringPool;

import java.util.HashMap;
import java.util.Map;

public abstract class AbstractMultiStepWrapper {

    protected MultiContext context;

    protected Map<String, String> onCompareFlagMap;

    public AbstractMultiStepWrapper(MultiContext context) {
        this.context = context;
        this.onCompareFlagMap = new HashMap<>();
    }

    protected  <T> void setContextISqlSegment(ISqlSegment sqlSegment, Class<T> tClass, String alisaName) {
        context.putTableAlisaName(tClass, alisaName);
        context.addEntityClass(tClass);
        context.addTableSqlAssembler(sqlSegment);
        context.addTableSqlAssembler(tClass);
    }

    public String getCompareOnSql(MultiFiledMappingStrategy mappingStrategy, CompareEnum compareEnum, FiledNature aNature, FiledNature bNature) {
        //添加and关键字
        return getAndSegment(aNature.getClazz(), bNature.getClazz()) + compareEnum.getMetaSql(
                mappingStrategy.getColumnName(context, aNature.getClazz(), aNature.getFiledName()),
                mappingStrategy.getColumnName(context, bNature.getClazz(), bNature.getFiledName()));
    }

    protected String getAndSegment(Class<?> aClass, Class<?> bClass) {
        String tableAlisaNameA = context.getEntityAlisaName(aClass);
        String tableAlisaNameB = context.getEntityAlisaName(bClass);
        String key = tableAlisaNameA + tableAlisaNameB;
        String onCompareFlag = onCompareFlagMap.get(key);
        if (onCompareFlag == null) {
            onCompareFlag = onCompareFlagMap.get(tableAlisaNameB + tableAlisaNameA);
        }
        if (onCompareFlag != null) {
            return SqlKeyword.AND.getSqlSegment() + StringPool.SPACE;
        } else {
            onCompareFlagMap.put(key, StringPool.FLAG);
            return StringPool.EMPTY;
        }
    }
}
